package com.seasun.xg.lamp.logserver;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.base.Strings;
import com.seasun.xg.lamp.repo.LogVo;

@RestController
@RequestMapping("/logserver")
public final class LogServerController {
	@Autowired
	private LogServerService service;

	@RequestMapping("/seqs/new")
	public String newSeq(HttpServletRequest request) {
		return service.newSeq(request.getRemoteAddr(), request.getLocalAddr(), request.getLocalPort());
	}

	@RequestMapping(value = "/seq/{seq}/push/device/v1", method = RequestMethod.POST)
	public void pushDeviceLog(@PathVariable String seq, @RequestBody LogVo vo, HttpServletRequest request) {
		vo.seq = seq;
		vo.source = "device";
		vo.publicIp = request.getRemoteAddr();
		vo.serverIp = request.getLocalAddr();
		vo.serverPort = request.getLocalPort();
		vo.appName = null;
		vo.appVersion = null;

		if (Strings.isNullOrEmpty(vo.deviceId) || Strings.isNullOrEmpty(vo.level)) {
			throw new TypeMismatchException("Field 'deviceId' and 'level' cannot be empty.");
		}

		service.pushDeviceLog(vo);
	}

	@RequestMapping(value = "/seq/{seq}/push/server/v1", method = RequestMethod.POST)
	public void pushServerLog(@PathVariable String seq, @RequestBody LogVo vo, HttpServletRequest request) {
		vo.seq = seq;
		vo.source = "server";
		vo.publicIp = request.getRemoteAddr();
		vo.serverIp = request.getLocalAddr();
		vo.serverPort = request.getLocalPort();
		vo.brand = null;
		vo.deviceId = null;
		vo.model = null;
		vo.network = null;
		vo.platform = null;

		if (Strings.isNullOrEmpty(vo.appName) || Strings.isNullOrEmpty(vo.appVersion)
				|| Strings.isNullOrEmpty(vo.level)) {
			throw new TypeMismatchException("Field 'appName', 'appVersion', 'level' cannot be empty.");
		}

		service.pushServerLog(vo);
	}
}
